<?php
/**
 * Created by PhpStorm.
 * User: dingboxu
 * Date: 16/9/15
 * Time: 下午7:48
 */

namespace Utils;

class HttpUtils {
    public static function LinkURL($url) {
        $fp = @fsockopen ( $url, 80, $errno, $errstr, 30 );
        if ($fp) {

            fputs ( $fp, "GET / HTTP/1.1\r\n" );
            fputs ( $fp, "Host: $url\r\n" );
            fputs ( $fp, "Accept: */*\r\n" );
            fputs ( $fp, "Referer: http://$url/\r\n" );
            fputs ( $fp, "User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)\r\n" );
            fputs ( $fp, "Connection: Close\r\n\r\n" );
        }
        while ( $str = fread ( $fp, 4096 ) )
            $data .= $str;
        fclose ( $fp );
        return $data;
    }

    public static function LinkHttpsUrl($url) {
        $ch = curl_init ();
        curl_setopt ( $ch, CURLOPT_URL, $url );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false );
        curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, false );

        $json = curl_exec ( $ch );
        curl_close ( $ch );
        return $json;
    }

    // 使用curl发送get请求
    public static function doGet_curl($httpUrl) {
        $ch = curl_init ();
        curl_setopt ( $ch, CURLOPT_URL, $httpUrl );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 ); // 禁止直接显示获取的内容 重要
        $result = curl_exec ( $ch ); // 获取
        curl_close ( $ch );
        // 直接将原始数据返回（部分渠道返回值非json型，无法统一转化）
        return $result;
    }

    // 使用curl发送post请求
    public static function doPost_curl($httpUrl, $post_data) {
        $ch = curl_init ();
        curl_setopt ( $ch, CURLOPT_URL, $httpUrl );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        // post传参
        curl_setopt ( $ch, CURLOPT_POST, 1 );
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $post_data );
        $result = curl_exec ( $ch );
        curl_close ( $ch );
        // 直接将原始数据返回（部分渠道返回值非json型，无法统一转化）
        return $result;
    }

    // 使用curl 发送异步 get调用
    public static function doAsyncGet_curl($url){
        $ch = curl_init();

        curl_setopt ( $ch, CURLOPT_URL, $url );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 ); // 禁止直接显示获取的内容 重要
        curl_setopt ( $ch, CURLOPT_TIMEOUT, 1 ); // 异步

        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    // 使用curl 发送异步 post请求
    public static function doAsyncPost_curl($httpUrl, $post_data) {
        $ch = curl_init ();
        curl_setopt ( $ch, CURLOPT_URL, $httpUrl );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch, CURLOPT_TIMEOUT, 1 ); // 异步
        // post传参
        curl_setopt ( $ch, CURLOPT_POST, 1 );
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $post_data );
        $result = curl_exec ( $ch );
        curl_close ( $ch );
        // 直接将原始数据返回（部分渠道返回值非json型，无法统一转化）
        return $result;
    }

}